/**
 * https://leetcode.cn/problems/find-pivot-index/
 */
function pivotIndex(nums: number[]): number {
  let total = nums.reduce((total, current) => total + current, 0);

  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    // sum ===  nums - num - sum ==> 左边 === 右边
    const num = nums[i];
    if (sum === total - num - sum) {
      return i;
    }
    sum += num;
  }

  return -1;
}

function pivotIndexV2(nums: number[]): number {
  let ans = -1;

  let start = 0,
    end = nums.length;

  let leftTotal = 0;
  let rightTotal = nums.reduce((total, current) => total + current, 0);
  while (start < end) {
    rightTotal -= nums[start];

    if (leftTotal === rightTotal) {
      return start;
    }

    leftTotal += nums[start];
    start++;
  }

  return ans;
}

function pivotIndexV1(nums: number[]): number {
  let ans = -1;

  let start = 0,
    end = nums.length;

  while (start < end) {
    let leftTotal = 0,
      rightTotal = 0;
    for (let i = 0; i < start; i++) {
      leftTotal += nums[i];
    }

    for (let i = start + 1; i < end; i++) {
      rightTotal += nums[i];
    }

    if (leftTotal === rightTotal) {
      return start;
    }
    start++;
  }

  return ans;
}
